package com.cugmarket.utils;

import cn.hutool.core.util.StrUtil;
import com.cugmarket.constant.RedisConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

@Slf4j
public class RefreshTokenInterceptor implements HandlerInterceptor {
    private StringRedisTemplate stringRedisTemplate;

    public RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
        // 这个拦截器不拦截，只用来保存用户信息到ThreadLocal，和刷新过期时间
        // 1.获取请求头中的token
        String token = request.getHeader("Authorization");
        log.info("拦截器获取到的token:{}", token);
        if (StrUtil.isBlank(token)) {
            return true;
        }
        // 2.基于token获取redis中的用户
        String key = RedisConstants.LOGIN_USER_KEY + token;
        String userId = stringRedisTemplate.opsForValue().get(key);
        log.info("查询到的ThreadLocal中的userId:{}", userId);
        // 3.判断用户是否存在
        // 不存在，放行
        if (userId == null) {
            // 同时要清空ThreadLocal中的用户信息
            UserHolder.removeUser();
            return true;
        }
        // 6.存在，保存用户信息到ThreadLocal
        UserHolder.saveUser(userId);
        // 7.刷新token有效期
        stringRedisTemplate.expire(key, RedisConstants.LOGIN_USER_TTL, TimeUnit.MINUTES);
        // 8.放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        UserHolder.removeUser();
    }
}
